""" 告警逻辑（延迟>500ms触发告警） """
"""告警管理器（异常检测/告警发送）"""
import time
from typing import Dict, List, Any, Optional
from fin_senti_entity_platform.utils.logger import Logger
from fin_senti_entity_platform.utils.constants import LOG_LEVELS


class AlertManager:
    """告警管理器类，用于管理和发送系统告警"""
    
    def __init__(self):
        """初始化告警管理器"""
        self.logger = Logger().get_logger(__name__)
        self.alert_channels = []
        self.alert_history = []
        self.silenced_alerts = set()
        self.max_history_size = 1000
    
    def register_channel(self, channel):
        """注册告警通道
        
        Args:
            channel: 告警通道对象，需要实现send_alert方法
        """
        if channel not in self.alert_channels:
            self.alert_channels.append(channel)
            self.logger.info(f"已注册告警通道: {channel.__class__.__name__}")
    
    def send_alert(self, message: str, level: str = 'WARNING', alert_id: Optional[str] = None,
                  details: Optional[Dict[str, Any]] = None):
        """发送告警
        
        Args:
            message: 告警消息
            level: 告警级别（DEBUG, INFO, WARNING, ERROR, CRITICAL）
            alert_id: 告警唯一标识，用于避免重复告警
            details: 告警详细信息
        """
        # 检查告警级别
        if level not in LOG_LEVELS:
            level = 'WARNING'
        
        # 检查是否被静默
        if alert_id and alert_id in self.silenced_alerts:
            return
        
        # 构建告警信息
        alert = {
            'id': alert_id or f"alert_{int(time.time())}_{hash(message) % 10000}",
            'message': message,
            'level': level,
            'timestamp': time.time(),
            'details': details or {}
        }
        
        # 记录告警历史
        self._record_alert(alert)
        
        # 记录到日志
        log_func = getattr(self.logger, level.lower())
        log_func(f"[ALERT] {message} {details}")
        
        # 通过所有注册的通道发送告警
        for channel in self.alert_channels:
            try:
                channel.send_alert(alert)
            except Exception as e:
                self.logger.error(f"通过通道 {channel.__class__.__name__} 发送告警失败: {str(e)}")
    
    def _record_alert(self, alert: Dict[str, Any]):
        """记录告警到历史记录"""
        self.alert_history.append(alert)
        # 保持历史记录不超过最大大小
        if len(self.alert_history) > self.max_history_size:
            self.alert_history = self.alert_history[-self.max_history_size:]
    
    def silence_alert(self, alert_id: str, duration: int = 3600):
        """静默指定告警
        
        Args:
            alert_id: 告警ID
            duration: 静默时长（秒），默认1小时
        """
        self.silenced_alerts.add(alert_id)
        
        # 设置定时器取消静默
        def unsilence():
            if alert_id in self.silenced_alerts:
                self.silenced_alerts.remove(alert_id)
                self.logger.info(f"告警 {alert_id} 静默已解除")
        
        import threading
        timer = threading.Timer(duration, unsilence)
        timer.daemon = True
        timer.start()
        
        self.logger.info(f"告警 {alert_id} 已静默 {duration} 秒")
    
    def get_alert_history(self, limit: int = 100) -> List[Dict[str, Any]]:
        """获取告警历史
        
        Args:
            limit: 返回的最大记录数
            
        Returns:
            List[Dict[str, Any]]: 告警历史记录
        """
        return self.alert_history[-limit:]
    
    def clear_alert_history(self):
        """清空告警历史"""
        self.alert_history.clear()
        self.logger.info("告警历史已清空")


# 示例告警通道实现
class ConsoleAlertChannel:
    """控制台告警通道"""
    
    def send_alert(self, alert: Dict[str, Any]):
        """发送告警到控制台"""
        print(f"[CONSOLE ALERT] [{alert['level']}] {alert['message']}")


# 创建全局实例
global_alert_manager = AlertManager()


def get_alert_manager() -> AlertManager:
    """获取告警管理器实例"""
    return global_alert_manager